# -- coding: utf-8 --

import base64
import datetime
import json
import multiprocessing
import os
from time import sleep

import cv2
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.opera.options import Options

import chaojiying
import connect_baishiht
import phone


# 获取验证码偏移量
def get_offset_position(a, b, username):
    # base64解码(解成二进制串)
    decode_jpg1 = base64.b64decode(a)
    decode_jpg2 = base64.b64decode(b)
    # 写入png文件
    with open(r'E:\UIpath Project\BaiSTH\%s\target.png' % username, 'wb') as f1:
        f1.write(decode_jpg1)
    with open(r'E:\UIpath Project\BaiSTH\%s\template.png' % username, 'wb') as f2:
        f2.write(decode_jpg2)
    
    otemp = r'E:\UIpath Project\BaiSTH\%s\template.png' % username
    oblk = r'E:\UIpath Project\BaiSTH\%s\target.png' % username
    target = cv2.imread(otemp, 0)
    template = cv2.imread(oblk, 0)
    w, h = target.shape[::-1]
    temp = r'E:\UIpath Project\BaiSTH\%s\temp.jpg' % username
    targ = r'E:\UIpath Project\BaiSTH\%s\targ.jpg' % username
    cv2.imwrite(temp, template)
    cv2.imwrite(targ, target)
    result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)
    x, y = np.unravel_index(result.argmax(), result.shape)
    print(y)
    # 展示圈出来的区域
    cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)  # 7, 249, 151
    return y


# 滑动验证码
def Slide_check(driver, username):
    sleep(3)
    a = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[1]/div[2]/img[1]").get_property('src').split(',')[-1]
    b = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[1]/div[2]/img[2]").get_property('src').split(',')[-1]
    
    c = get_offset_position(a, b, username)  # 测出偏移量
    # 如果偏移量为0，会导致验证码不会刷新
    if c == 0:
        c = 10
    sleep(1)
    div = driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div[4]/div[2]')
    ActionChains(driver).drag_and_drop_by_offset(div, xoffset=c, yoffset=0).perform()


# 用户登录
def user_login(driver, url, username, password):
    driver.get(url)
    driver.maximize_window()
    sleep(2)
    driver.find_element_by_xpath('//*[@id="root"]/section/div/div[2]/form/div[1]/div/div/span/div/span/span[1]').click()
    sleep(2)
    driver.find_element_by_xpath("//*[@id='app']/div[2]/div[1]/div[2]/div/div[1]/img").click()
    sleep(2)
    driver.find_element_by_xpath("//*[@id='app']/div[2]/div[1]/div[2]/div/div[2]/form/div[1]/div/div/input").send_keys(
        username)
    sleep(2)
    driver.find_element_by_xpath("//*[@id='app']/div[2]/div[1]/div[2]/div/div[2]/form/div[2]/div/div/input").send_keys(
        password)
    sleep(2)
    driver.find_element_by_xpath("//*[@id='app']/div[2]/div[1]/div[2]/div/div[2]/form/button").click()

    for i in range(10):
        try:
            sleep(3)
            Slide_check(driver, username)
            if driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[1]") is not None:  # 如果还有验证码，重试
                continue
        except Exception as e:
            sleep(2)
            text = ''
            try:
                text = driver.find_element_by_xpath("//*[@id='app']/div[2]/div[1]/div[2]/div/div[2]/form/div[1]").text
            except Exception as er:
                pass
            if len(text) > 0:
                raise Exception("登录异常：" + text + "，当前账号：" + username)
            else:
                break


# 主流程
def baishi_rpa(browser, url, username, password):
    driver = None
    # 你可以自定义这里，添加更多浏览器支持进来
    if browser == "ie":
        driver = webdriver.Ie()
    elif browser == "firefox":
        driver = webdriver.Firefox()
    elif browser == "chrome":
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_experimental_option("detach", True)
        driver = webdriver.Chrome(options=chrome_options)
    elif browser == 'opera':
        options = Options()
        options.add_experimental_option("detach", True)
        driver = webdriver.Opera(options=options)
    elif browser == 'msedge':
        driver = webdriver.Edge()
    
    if driver == None:
        exit()
    
    # 账号登录
    user_login(driver, url, username, password)
    
    sleep(2)
    # 获取当前url
    new_url = driver.current_url
    
    # 选择该账号下需要处理的站点
    while True:
        t1 = '08:00'
        t2 = '20:30'
        site_list = connect_baishiht.select_site(username)
        print("                                                 ")
        print("账号%s需要处理的站点列表为%s" % (username, site_list))
        for standby_site in site_list:
            count = 0
            # 匹配站点选择登录
            sleep(3)
            site_count = len(driver.find_element_by_xpath(
                '//*[@id="container_demo"]/div/div/div/ul/div[2]/div/div/div[2]/div/div/div/span/div/table/tbody').find_elements_by_tag_name(
                "tr"))
            print("                                     ")
            print("正在进行站点（%s）的匹配" % standby_site)
            for site in range(1, site_count + 1):
                sleep(4)
                site_name_xpath = '//*[@id="container_demo"]/div/div/div/ul/div[2]/div/div/div[2]/div/div/div/span/div/table/tbody/tr[%s]/td[1]/div/span/span[1]' % site
                site_name = driver.find_element_by_xpath(site_name_xpath).text
                if standby_site == site_name:
                    print("站点(%s)正在处理工单" % site_name)
                    # 点击登录
                    site_login = '//*[@id="container_demo"]/div/div/div/ul/div[2]/div/div/div[2]/div/div/div/span/div/table/tbody/tr[%s]/td[2]/div' % site
                    driver.find_element_by_xpath(site_login).click()
                    
                    sleep(10)
                    
                    print('判断是否有验证码')
                    try:
                        # 移动到菜单栏
                        driver.find_element_by_xpath('//*[@id="header-menu"]/div[1]')
                    except Exception as e:
                        set_code(driver, username)
                    
                    sleep(2)
                    # 移动到菜单栏
                    mouse = driver.find_element_by_xpath('//*[@id="header-menu"]/div[1]')
                    ActionChains(driver).move_to_element(mouse).perform()
                    
                    sleep(2)
                    # 点击站点问题受理
                    driver.find_element_by_xpath('//*[@id="submenu-6600$Menu"]/li[2]').click()
                    
                    sleep(3)
                    # 移出到菜单栏
                    mouse = driver.find_element_by_xpath(
                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/button')
                    ActionChains(driver).move_to_element(mouse).perform()
                    
                    sleep(2)
                    # 点击组内未处理
                    driver.find_element_by_xpath(
                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[2]/span').click()
                    
                    sleep(2)
                    # 拾取"组内未处理"表格内容
                    html = driver.find_element_by_xpath(
                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div').get_property(
                        'innerHTML')
                    bs = str(BeautifulSoup(html, 'lxml').find_all('table'))
                    df = pd.DataFrame()
                    for i in pd.read_html(bs):
                        all_df = df.append(i)
                    sleep(3)
                    required_df = all_df[['运单号', '录入组']]
                    print(required_df)
                    required_df.to_excel(r'E:/UIpath Project/BaiSTH/%s/required_df.xlsx' % username, index=False,
                                         header=True)
                    
                    # 判断录入组为前台/站点输入单号处理
                    for row in required_df.itertuples():
                        group = getattr(row, "录入组")
                        waybill = getattr(row, "运单号")
                        now = datetime.datetime.now().strftime("%H:%M")
                        if group == "前台组":
                            if t1 < now < t2:
                                print("外呼时间")
                                print("前台组:运单号为%s的工单正在处理" % waybill)
                                
                                sleep(2)
                                driver.find_element_by_xpath('//*[@id="expressCode"]').clear()
                                
                                sleep(2)
                                # 输入运单号
                                driver.find_element_by_xpath('//*[@id="expressCode"]').send_keys(waybill)
                                
                                sleep(3)
                                # 判断有无人为干预
                                try:
                                    # 点击处理
                                    sleep(2)
                                    driver.find_element_by_xpath(
                                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                                    # 如果工单被用户抢单则跳过
                                except Exception:
                                    sleep(2)
                                    # 点击我的未处理
                                    driver.find_element_by_xpath(
                                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[3]/span').click()
                                    
                                    sleep(2)
                                    # 返回组内未处理
                                    driver.find_element_by_xpath(
                                        '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[2]/span').click()
                                    continue
                                
                                # sleep(1)
                                # # 点击处理
                                # driver.find_element_by_xpath('//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                                
                                sleep(2)
                                # 获取数据
                                group_type = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[4]/div/div[2]/div/span').text
                                phone_number = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[3]/div/div[2]/div/span').text
                                tracking_number = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[5]/div/div[2]/div/span').text
                                problem_type = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[2]/div/div[2]/div/span').text
                                problem_desc = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[9]/div/div[2]/div/span').text
                                call_time = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[4]/div/div[2]/div/span').text
                                receiving_address = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[6]/div/div[2]/div/span').text
                                base_type = driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[2]/div/div[2]/div/span').text
                                
                                sleep(2)
                                # 写入数据库
                                connect_baishiht.insert_data(username, site_name, tracking_number, problem_type,
                                                             problem_desc, group_type, phone_number, call_time,
                                                             receiving_address)
                                
                                location = ''
                                # 查询电话归属地
                                try:
                                    res = phone.Phone().find(phone_number)
                                    location = res['province'] + ' ' + res['city']
                                except:
                                    pass
                                
                                
                                # 写入服务器数据
                                headers = {'Content-Type': 'application/json'}
                                datas = {"userName": username,
                                         "site": site_name,
                                         "inputGroup": group_type,
                                         "trackingNumber": tracking_number,
                                         "problemType": problem_type,
                                         "artificialStatus": "未跟进",
                                         "baseType": base_type,
                                         "baseCallNumber": phone_number,
                                         "baseTrackingNumber": tracking_number,
                                         "baseCallTime": call_time,
                                         "baseReceivingAddress": receiving_address,
                                         "problemInfoType": problem_type,
                                         "problemInfoDescribe": problem_desc,
                                         "phoneLocation": location
                                         }
                                sleep(2)
                                requests.post("http://193.112.1.68:8905/order/create", data=json.dumps(datas),
                                              headers=headers)
                                print("等待外呼")
                                
                                sleep(1)
                                # 点击返回
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[2]/div/button[4]').click()
                                
                                sleep(1)
                                # 点击我的未处理
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[3]/span').click()
                                
                                sleep(1)
                                # 返回组内未处理
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[2]/span').click()
                            
                            else:
                                print('不打扰客户休息')
                        
                        elif group == "站点组":
                            print("站点组:运单号为%s的工单正在处理" % waybill)
                            # 输入运单号
                            driver.find_element_by_xpath('//*[@id="expressCode"]').send_keys(waybill)
                            
                            sleep(1)
                            # 判断有无人为干预
                            try:
                                # 点击处理
                                sleep(2)
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                                # 如果工单被用户抢单则跳过
                            except Exception:
                                sleep(2)
                                driver.find_element_by_xpath('//*[@id="expressCode"]').clear()
                                sleep(1)
                                continue
                            
                            # sleep(1)
                            # #点击处理
                            # driver.find_element_by_xpath('//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                            
                            sleep(1)
                            # 点击返回
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[2]/div/button[4]').click()
                            
                            sleep(1)
                            # 点击我的未处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[3]/span').click()
                            
                            sleep(1)
                            # 输入运单号
                            driver.find_element_by_xpath('//*[@id="expressCode"]').send_keys(waybill)
                            
                            sleep(1)
                            # 点击处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                            
                            sleep(1)
                            # 获取数据
                            group_type = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[4]/div/div[2]/div/span').text
                            phone_number = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[3]/div/div[2]/div/span').text
                            tracking_number = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[5]/div/div[2]/div/span').text
                            problem_type = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[2]/div/div[2]/div/span').text
                            problem_desc = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[3]/div[2]/div/div[9]/div/div[2]/div/span').text
                            call_time = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[4]/div/div[2]/div/span').text
                            receiving_address = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[6]/div/div[2]/div/span').text
                            base_type = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[2]/div/div[2]/div/span').text
                            
                            sleep(1)
                            # 写入数据库
                            connect_baishiht.insert_data(username, site_name, tracking_number, problem_type,
                                                         problem_desc, group_type, phone_number, call_time,
                                                         receiving_address)
                            
                            # 写入服务器数据
                            headers = {'Content-Type': 'application/json'}
                            datas = {"userName": username,
                                     "site": site_name,
                                     "inputGroup": group_type,
                                     "trackingNumber": tracking_number,
                                     "problemType": problem_type,
                                     "artificialStatus": "未跟进",
                                     "baseType": base_type,
                                     "baseCallNumber": phone_number,
                                     "baseTrackingNumber": tracking_number,
                                     "baseCallTime": call_time,
                                     "baseReceivingAddress": receiving_address,
                                     "problemInfoType": problem_type,
                                     "problemInfoDescribe": problem_desc,
                                     }
                            
                            zd_response = requests.post("http://193.112.1.68:8905/order/create", data=json.dumps(datas),
                                                        headers=headers)
                            zd_id = json.loads(zd_response.text)["content"]
                            
                            sleep(2)
                            # 点击无责
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[4]/div[2]/div[3]/div[2]/div/span/div/div[2]/label/span[1]/input').click()
                            
                            sleep(2)
                            # 填入反馈
                            driver.find_element_by_xpath('//*[@id="continue_remark"]').send_keys(
                                "我司已通知业务员处理，预计20个工作小时内处理完毕。")
                            
                            sleep(1)
                            # 提交数据
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[2]/div/button[2]').click()
                            
                            sleep(1)
                            # 更新数据库状态
                            connect_baishiht.alter_status(tracking_number, "完成")
                            
                            # 更新服务器数据
                            zd_finish_url = "http://193.112.1.68:8905/order/finish/%s" % zd_id
                            requests.get(url=zd_finish_url)
                            
                            sleep(1)
                            # 返回组内未处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[2]/span').click()
                    
                    sleep(2)
                    print("判断外呼")
                    # 循环完了以后，判断有无已外呼的工单
                    datas = {'userName': username, 'site': site_name}
                    headers = {'Content-Type': 'application/json'}
                    print(datas)
                    call_response = requests.post("http://193.112.1.68:8905/order/getQTData", data=json.dumps(datas),
                                                  headers=headers)
                    print(call_response.text)
                    await_callorder = json.loads(call_response.text)["content"]
                    
                    if len(await_callorder) >= 1:  # 证明有外呼成功数据
                        for item in await_callorder:
                            qt_id = item['ticketId']
                            trackingNumber = item['trackingNumber']
                            
                            sleep(1)
                            # 点击我的未处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[3]/span').click()
                            
                            sleep(1)
                            # 输入运单号
                            driver.find_element_by_xpath('//*[@id="expressCode"]').send_keys(trackingNumber)
                            
                            try:
                                sleep(1)
                                # 点击处理
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                                # 如果工单被用户抢单则跳过
                            except Exception:
                                sleep(1)
                                # 更新服务器数据
                                rg_id = qt_id
                                rg_finish_url = "http://193.112.1.68:8905/order/finish/%s" % rg_id
                                requests.get(url=rg_finish_url)
                                
                                sleep(2)
                                driver.find_element_by_xpath('//*[@id="expressCode"]').clear()
                                sleep(1)
                                continue
                            
                            # sleep(1)
                            # # 点击处理
                            # driver.find_element_by_xpath('//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a').click()
                            
                            sleep(1)
                            # 获取数据
                            phone_number = driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[2]/div[2]/div/div[3]/div/div[2]/div/span').text
                            
                            sleep(2)
                            # 点击无责
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[1]/div[4]/div[2]/div[3]/div[2]/div/span/div/div[2]/label/span[1]/input').click()
                            
                            sleep(2)
                            # 填入反馈
                            driver.find_element_by_xpath('//*[@id="continue_remark"]').send_keys(
                                "此件已回电客户%s，告知我司已优先处理，客户认可" % phone_number)
                            
                            sleep(1)
                            # 提交数据
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div/form/div[2]/div/button[2]').click()
                            
                            # todo
                            
                            sleep(2)
                            # 返回组内未处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[2]/span').click()
                            
                            sleep(2)
                            # 点击我的未处理
                            driver.find_element_by_xpath(
                                '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[1]/div[1]/div/span/span[3]/span').click()
                            
                            sleep(2)
                            # 输入运单号
                            driver.find_element_by_xpath('//*[@id="expressCode"]').send_keys(trackingNumber)
                            
                            try:
                                sleep(1)
                                # 点击处理
                                driver.find_element_by_xpath(
                                    '//*[@id="root"]/div/section/div/div[3]/div[2]/div[2]/div[1]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a')
                                continue
                            except Exception:
                                sleep(2)
                                # 更新数据库状态
                                connect_baishiht.alter_status(trackingNumber, "完成")
                                
                                sleep(2)
                                # 更新服务器数据
                                qt_finish_url = "http://193.112.1.68:8905/order/finish/%s" % qt_id
                                requests.get(url=qt_finish_url)
                            
                            # sleep(1)
                            # # 更新数据库状态
                            # connect_baishiht.alter_status(trackingNumber, "完成")
                            #
                            # sleep(1)
                            # # 更新服务器数据
                            # qt_finish_url = "http://193.112.1.68:8905/order/finish/%s" % qt_id
                            # requests.get(url=qt_finish_url)
                        
                        # 回到站点选择画面
                        driver.get(new_url)
                        print("返回首页")
                    else:
                        # 回到站点选择画面
                        driver.get(new_url)
                        print("返回首页")
                
                else:
                    count += 1
                    print("站点(%s)无需处理" % site_name)
                if count == site_count:
                    print('站点不存在异常，当前站点：%s' % standby_site)


#
def set_code(driver, username):
    tryNumber = 0
    while True:
        try:
            sleep(2)
            driver.find_element_by_xpath(
                '/html/body/div[3]/div/div[2]/div/div[1]/div[2]/form/div[3]/div[2]/div/div/div[2]/i/img').click()
            img_path = r'E:\UIpath Project\BaiSTH\%s\text_code.png' % username
            sleep(2)
            # 获取验证码截图
            driver.find_element_by_xpath(
                '/html/body/div[3]/div/div[2]/div/div[1]/div[2]/form/div[3]/div[2]/div/div/div[2]/i/img').screenshot(
                img_path)
            sleep(1)
            # 识别验证码
            code = chaojiying.getText(img_path)[0]
            sleep(1)
            # 判断验证码不为空且是数字且长度为4
            print('识别验证码为：' + code)
            if code != '' and code.isdigit() and len(code.strip()) == 4:
                sleep(1)
                driver.find_element_by_xpath('//*[@id="captcha"]').clear()
                # 输入验证码
                driver.find_element_by_xpath('//*[@id="captcha"]').send_keys(code)
                sleep(2)
                # 点击授权
                driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/div/div[1]/div[2]/form/p[1]/button').click()
                sleep(5)
                # 判断是否登录成功
                driver.find_element_by_xpath('//*[@id="header-menu"]/div[1]')
                break
        except Exception as e:
            continue
        finally:
            tryNumber += 1
            if tryNumber == 2:
                raise Exception("验证码异常：验证码次数已用完")



# 外循环
def baishi_retry(browser, url, username, password):
    tryNumber = 0
    while True:

        try:
            baishi_rpa(browser, url, username, password)
        except Exception as e:
            os.popen('TASKKILL /F /IM %s.exe /T' % browser)
            if '登录异常' in str(e):
                print('login Exception', str(e))
                add_exception_msg(username, str(e))
                break
            elif '验证码异常' in str(e):
                print('code Exception:', str(e))
                callYunWei(0)
                break
            else:
                tryNumber += 1
                print("重试一次", str(e))
                continue
        if tryNumber == 10:
            print('流程异常，联系运维人员')
            callYunWei(1)
            break

# 添加异常信息
def add_exception_msg(user_name, msg):
    headers = {'Content-Type': 'application/json'}
    data = {'userName': user_name, 'message': msg}
    response = requests.post("http://localhost:8905/order/addMessage", data=json.dumps(data),
                             headers=headers)

# 发短信通知运维（0：验证码异常，1：流程异常）
def callYunWei(type):
    headers = {'Content-Type': 'application/json'}
    data = {'type': type}
    response = requests.post("http://localhost:8905/callback/alarm", data=json.dumps(data),
                             headers=headers)

if __name__ == "__main__":
    
    data = {
        # "chrome": ["https://icrm.800best.com/#/login", "test", "PQ518840.."],
        #  "opera": ["https://icrm.800best.com/#/login", "18807842779", "Yn518840@"],
         "chrome": ["https://icrm.800best.com/#/login", "test", "PQ518840.."],
         # "firefox": ["https://icrm.800best.com/#/login", "chenXH2020", "Cxh363569"],
        # "firefox":"https://icrm.800best.com/#/login",
        # "msedge":["https://icrm.800best.com/#/login",
    }
    
    # 构建进程
    pool = multiprocessing.Pool(processes=3)
    for browser, lo_data in data.items():
        url = lo_data[0]
        username = lo_data[1]
        password = lo_data[2]
        # pool.apply_async(baishi_rpa, (browser, url, username, password))
        pool.apply_async(baishi_retry, (browser, url, username, password))  # 加上试错3次
    pool.close()
    pool.join()
